//=============================================================================
//
//   File : qtg_treewidget.cpp
//   Creation date : Sab 19 mar 2011 09:31:42 CET by Antonino G.Imbesi
//
//   This file is part of the QtGLauncher distribution
//   Copyright (C) 2011 Antonino G. Imbesi <grifisx at barmes dot org>
//
//   This program is FREE software. You can redistribute it and/or
//   modify it under the terms of the GNU General Public License
//   as published by the Free Software Foundation; either version 2
//   of the License, or (at your opinion) any later version.
//
//   This program is distributed in the HOPE that it will be USEFUL,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//   See the GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program. If not, write to the Free Software Foundation,
//   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
//=============================================================================

#include "qtg_treewidget.h"
#include "qtg_listviewitem.h"
#include <QPainter>
#include <QDebug>

qtg_QTreeWidget::qtg_QTreeWidget(QWidget *parent) :
        QTreeWidget(parent)
{
    setHeaderHidden(1);
    setMouseTracking(1);
}

qtg_QTreeWidget::~qtg_QTreeWidget()
{

}
void qtg_QTreeWidget::mouseMoveEvent(QMouseEvent *)
{
    // qDebug() << this->currentItem()->text(0);
    //this->setCurrentItem(this->selectedItems().at(0),0);
    // dummy just to avoid bug #581:
    //   Clicking on item A and moving the mouse to item B selects item A first and then item B
    //   Hovewer item A remains current
}

void qtg_QTreeWidget::drawRow(QPainter* p, const QStyleOptionViewItem &opt, const QModelIndex &idx) const
{
    // Riscrivo la funzione per avere degli item completamente trasparenti e poter vedere lo sfondo della treewidget
    /* Altro metodo per disegnare la pixmap:
   la recupero così:
   QTreeWidgetItem * item = this->itemFromIndex(idx);
   la drawo così:
   p->drawPixmap(im,yPixmap,16,16,item->icon(0).pixmap(16,16));

*/
    for (int col = 0; col < columnCount(); ++col)
    {

        QModelIndex s = idx.sibling(idx.row(), col);

        if (s.isValid())
        {
            // Recupero il testo dell'item
            QString szText=idx.data(Qt::DisplayRole).toString();
            // Recupero la pixmap dell'item
            QPixmap myPix =  qvariant_cast<QIcon>(idx.data(Qt::DecorationRole)).pixmap(opt.decorationSize);
            // Mi recupero il rettangolo dove disegnare
            int x = visualRect(s).left();
            int y = visualRect(s).top();
            int w = visualRect(s).width();
            int h = visualRect(s).height();
            QRect cRect(x,y,w,h);

            // Mi calcolo la y dell'icona dell'item
            int yPixmap = (y + (h / 2 - 8));
            /* Posso cominciare a disegnare l'item, non disegnerò lo sfondo
                    perchè lo voglio trasparente, altrimenti avrei fatto così:
                    QImage image("percorso");
                    QRect rect(opt.rect);
                    p->drawImage(rect, image);
                 */
            // Se l'item è selezionato lo coloro con i colori di sistema
            QStyleOptionViewItemV4 opt4(opt);
            opt4.state = opt4.state | QStyle::State_Selected;
            if(itemFromIndex(idx)->isSelected()){
                opt4.state = opt4.state | QStyle::State_Selected;
                //    style()->drawPrimitive(QStyle::PE_PanelItemViewRow, &opt4, p, this);
                QBrush brush = opt.palette.highlight();
                QColor col=brush.color();
                col.setAlpha(160);
                brush.setColor(col);
                p->fillRect(opt.rect, brush);
            }

            // Disegno l'icona
            p->drawPixmap(x,yPixmap,myPix.width(),myPix.height(),myPix);
            // Mi sposto verso destra del rettangolo dell'item della lunghezza della pixmap + 2 per distaccarmi
            // e disegno il testo
            cRect.setLeft(cRect.left() + myPix.width()+2);
            p->drawText(cRect,Qt::AlignLeft | Qt::AlignVCenter,szText);;
            // Mi sposto verso sinistra del rettangolo visuale dell'item sottraendo la lunghezza della mia pixmap + 2
            // e ciamo la funzione delle QT che disegna le branches passandogli il rettangolo giusto
            cRect.setRight(cRect.left() - (myPix.width()+2));
            QTreeView::drawBranches(p,cRect,idx);

        }

    }

}
void qtg_QTreeWidget::filterIterator(QString filter)
{
    QTreeWidgetItemIterator it(this);
    while (*it)
    {
        if(filter.length()>=3)
        {
            if ((*it)->text(0).contains(filter,Qt::CaseInsensitive))
            {
                (*it)->setSelected(1);
                QTreeWidgetItem *item=(*it);
                while(item->parent()){
                    item->parent()->setExpanded(1);
                    if(item->parent())
                        item= item->parent();
                    else
                    {
                        delete item;
                        continue;
                    }
                }
            }
        }
        if (!(*it)->text(0).contains(filter,Qt::CaseInsensitive))
        {
            (*it)->setSelected(0);
        }
        if(filter.length()<3)
        {
            clearSelection();
            collapseAll();
        }
        ++it;
    }

}

void qtg_QTreeWidget::focusInEvent ( QFocusEvent * event )
{
    setCurrentItem(topLevelItem(0));
}
